import { lazy } from "@/util/lazy.ts";
import { useUserStore } from "@/store";
import { ChatMessageType } from "@/pages/room/components/chat/chat-message.ts";

import type HistoryUserStore from "@/pages/room/HistoryUserStore.ts";
import type { UserModel } from "@/api/model/user.model.ts";
import type { ReactiveData } from "@/pages/room/model.ts";
import type { ServerEventListener } from "@/pages/room/ws/ws.ts";

const userStore = lazy(() => useUserStore());

export function createMessageListener(
    data: ReactiveData,
    historyUserStore: HistoryUserStore,
    triggerAfter: (type: ChatMessageType, sender: UserModel, content: string) => void
): ServerEventListener<"message"> {
    return function (details) {
        if (details.sender === userStore()._user?.id) {
            data.chats.push({
                type: ChatMessageType.SELF,
                sender: userStore()._user!!,
                metadata: {},
                content: details.message
            });
            triggerAfter(ChatMessageType.SELF, userStore()._user!!, details.message);
        } else {
            data.chats.push({
                type: ChatMessageType.OTHER,
                sender: historyUserStore.get(details.sender)!!,
                metadata: {},
                content: details.message
            });
            triggerAfter(ChatMessageType.OTHER, historyUserStore.get(details.sender)!!, details.message);
        }
    }
}